package hashbuck;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yi
 * Date: 2024-08-01
 * Time: 11:50
 */
public class HashBuck {
    static class Node {
        public int key;
        public int value;
        public Node next;

        public Node(int key,int val) {
            this.key = key;
            this.value = val;
        }
    }

    public Node[] elem;
    public int usedSize;

    public HashBuck() {
        this.elem = new Node[10];
    }

    //往哈希桶里面放元素
    public void put(int key,int val) {
        Node node = new Node(key,val);
        int tmp = key % this.elem.length;
        Node cur = this.elem[tmp];
        while(cur.next != null) {
            if(cur.value == val) {
                cur.value = val;
                return;
            }
            cur = cur.next;
        }
        cur.next = node;
        this.usedSize++;
        //负载因子超过了0.75，需要扩容
        if(loadFactor() >= 0.75) {
            //调用扩容函数
            resize();
        }
    }
    //扩容函数
    private void resize() {
        Node[] tmpArr = new Node[this.elem.length*2];
        for (int i = 0; i < this.elem.length; i++) {
            Node cur = this.elem[i];
            while(cur != null) {
                //记录cur.next的位置
                Node curNext = cur.next;
                int newIndex = cur.key / tmpArr.length;
                //头插法
                cur.next = tmpArr[newIndex];
                tmpArr[newIndex] = cur;
                cur = curNext;
            }
        }

        this.elem = tmpArr;
    }
    //求出当前负载因子
    private double loadFactor() {
        return this.usedSize*1.0 / this.elem.length;
    }

    //给定一个key值在哈希桶里面找到并返回其value值
    public int get(int key) {
        int index = key % this.elem.length;
        Node cur = this.elem[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}
